from app.schemas.moment import MomentCreate, MomentUpdate, Moment, LikeCreate, Like, CommentCreate, CommentUpdate, Comment
from app.database.connection import get_database
from datetime import datetime
from bson import ObjectId

async def create_moment(moment: MomentCreate, user_id: str) -> Moment:
    """创建动态"""
    db = get_database()
    
    # 创建动态文档
    moment_dict = moment.dict()
    moment_dict["user_id"] = ObjectId(user_id)
    moment_dict["like_count"] = 0
    moment_dict["comment_count"] = 0
    moment_dict["created_at"] = datetime.utcnow()
    moment_dict["updated_at"] = datetime.utcnow()
    
    # 插入数据库
    result = await db["moments"].insert_one(moment_dict)
    
    # 获取创建的动态
    created_moment = await db["moments"].find_one({"_id": result.inserted_id})
    
    # 转换为Moment对象
    moment_response = created_moment.copy()
    moment_response["id"] = str(moment_response["_id"])
    moment_response["user_id"] = str(moment_response["user_id"])
    
    return Moment(**moment_response)

async def get_moments(skip: int = 0, limit: int = 100) -> list[Moment]:
    """获取动态列表"""
    db = get_database()
    moments_cursor = db["moments"].find().skip(skip).limit(limit)
    moments = await moments_cursor.to_list(length=limit)
    
    result = []
    for moment_doc in moments:
        moment_response = moment_doc.copy()
        moment_response["id"] = str(moment_response["_id"])
        moment_response["user_id"] = str(moment_response["user_id"])
        result.append(Moment(**moment_response))
    
    return result

async def get_moment(moment_id: str) -> Moment:
    """获取动态详情"""
    db = get_database()
    try:
        moment_doc = await db["moments"].find_one({"_id": ObjectId(moment_id)})
        if moment_doc:
            moment_response = moment_doc.copy()
            moment_response["id"] = str(moment_response["_id"])
            moment_response["user_id"] = str(moment_response["user_id"])
            return Moment(**moment_response)
        return None
    except Exception:
        return None

async def update_moment(moment_id: str, moment_update: MomentUpdate) -> Moment:
    """更新动态"""
    db = get_database()
    
    # 构建更新字典
    update_data = {k: v for k, v in moment_update.dict().items() if v is not None}
    if not update_data:
        return await get_moment(moment_id)
    
    update_data["updated_at"] = datetime.utcnow()
    
    # 更新数据库
    result = await db["moments"].update_one(
        {"_id": ObjectId(moment_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        return None
    
    return await get_moment(moment_id)

async def delete_moment(moment_id: str) -> bool:
    """删除动态"""
    db = get_database()
    result = await db["moments"].delete_one({"_id": ObjectId(moment_id)})
    return result.deleted_count > 0

async def create_like(like: LikeCreate) -> Like:
    """创建点赞"""
    db = get_database()
    
    # 检查是否已点赞
    existing_like = await db["likes"].find_one({
        "user_id": ObjectId(like.user_id),
        "moment_id": ObjectId(like.moment_id)
    })
    
    if existing_like:
        raise ValueError("Already liked this moment")
    
    # 创建点赞文档
    like_dict = like.dict()
    like_dict["user_id"] = ObjectId(like_dict["user_id"])
    like_dict["moment_id"] = ObjectId(like_dict["moment_id"])
    like_dict["created_at"] = datetime.utcnow()
    
    # 插入数据库
    result = await db["likes"].insert_one(like_dict)
    
    # 获取创建的点赞
    created_like = await db["likes"].find_one({"_id": result.inserted_id})
    
    # 转换为Like对象
    like_response = created_like.copy()
    like_response["id"] = str(like_response["_id"])
    like_response["user_id"] = str(like_response["user_id"])
    like_response["moment_id"] = str(like_response["moment_id"])
    
    # 增加动态的点赞数
    await db["moments"].update_one(
        {"_id": ObjectId(like.moment_id)},
        {"$inc": {"like_count": 1}}
    )
    
    return Like(**like_response)

async def create_comment(comment: CommentCreate, user_id: str) -> Comment:
    """创建评论"""
    db = get_database()
    
    # 创建评论文档
    comment_dict = comment.dict()
    comment_dict["user_id"] = ObjectId(user_id)
    comment_dict["moment_id"] = ObjectId(comment_dict["moment_id"])
    if "parent_comment_id" in comment_dict and comment_dict["parent_comment_id"]:
        comment_dict["parent_comment_id"] = ObjectId(comment_dict["parent_comment_id"])
    comment_dict["created_at"] = datetime.utcnow()
    
    # 插入数据库
    result = await db["comments"].insert_one(comment_dict)
    
    # 获取创建的评论
    created_comment = await db["comments"].find_one({"_id": result.inserted_id})
    
    # 转换为Comment对象
    comment_response = created_comment.copy()
    comment_response["id"] = str(comment_response["_id"])
    comment_response["user_id"] = str(comment_response["user_id"])
    comment_response["moment_id"] = str(comment_response["moment_id"])
    if comment_response["parent_comment_id"]:
        comment_response["parent_comment_id"] = str(comment_response["parent_comment_id"])
    
    # 增加动态的评论数
    await db["moments"].update_one(
        {"_id": ObjectId(comment.moment_id)},
        {"$inc": {"comment_count": 1}}
    )
    
    return Comment(**comment_response)

async def update_comment(comment_id: str, comment_update: CommentUpdate) -> Comment:
    """更新评论"""
    db = get_database()
    
    # 构建更新字典
    update_data = {k: v for k, v in comment_update.dict().items() if v is not None}
    if not update_data:
        return await get_comment(comment_id)
    
    # 更新数据库
    result = await db["comments"].update_one(
        {"_id": ObjectId(comment_id)},
        {"$set": update_data}
    )
    
    if result.modified_count == 0:
        return None
    
    return await get_comment(comment_id)

async def delete_comment(comment_id: str) -> bool:
    """删除评论"""
    db = get_database()
    
    # 获取评论信息
    comment = await db["comments"].find_one({"_id": ObjectId(comment_id)})
    if not comment:
        return False
    
    # 删除评论
    result = await db["comments"].delete_one({"_id": ObjectId(comment_id)})
    
    if result.deleted_count > 0:
        # 减少动态的评论数
        await db["moments"].update_one(
            {"_id": ObjectId(comment["moment_id"])},
            {"$inc": {"comment_count": -1}}
        )
        return True
    
    return False

async def get_comment(comment_id: str) -> Comment:
    """获取评论详情"""
    db = get_database()
    try:
        comment_doc = await db["comments"].find_one({"_id": ObjectId(comment_id)})
        if comment_doc:
            comment_response = comment_doc.copy()
            comment_response["id"] = str(comment_response["_id"])
            comment_response["user_id"] = str(comment_response["user_id"])
            comment_response["moment_id"] = str(comment_response["moment_id"])
            if comment_response["parent_comment_id"]:
                comment_response["parent_comment_id"] = str(comment_response["parent_comment_id"])
            return Comment(**comment_response)
        return None
    except Exception:
        return None